package com.ss.android.common.util;

import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.Pair;

import com.bytedance.common.utility.Logger;
import com.bytedance.common.utility.NetworkType;
import com.bytedance.frameworks.baselib.network.http.AppConfig;
import com.bytedance.frameworks.baselib.network.http.util.TaskInfo;
import com.bytedance.retrofit2.ResponseWrapper;
import com.bytedance.retrofit2.client.Header;
import com.bytedance.retrofit2.mime.TypedByteArray;
import com.bytedance.retrofit2.mime.TypedFile;
import com.bytedance.retrofit2.mime.TypedOutput;
import com.bytedance.retrofit2.mime.TypedString;
import com.bytedance.ttnet.INetworkApi;
import com.bytedance.ttnet.b.RequestParams;
import com.bytedance.ttnet.utils.RetrofitUtils;
import com.ss.android.http.legacy.HttpHeader;
import com.ss.android.http.legacy.NameValue;
import com.ss.android.http.legacy.a.LegacyHeader;
import com.ss.android.http.legacy.a.NameValueImpl;
import com.ss.android.http.legacy.a.ResponseHeaders;
import com.ss.android.http.legacy.c;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.zip.Deflater;
import java.util.zip.GZIPOutputStream;

import inline.NetworkDemo;

public final class NetworkUtils {
    private static volatile boolean a = true;
    private static volatile boolean b = false;
    private static volatile int c = -1;

    public static void a(List arg4) {
        LinkedHashMap v0 = new LinkedHashMap();
        AppConfig.a(v0);
        Iterator v2 = ((Map) v0).entrySet().iterator();
        while (v2.hasNext()) {
            Map.Entry<String, String> v0_1 = (Map.Entry<String, String>) v2.next();
            if (v0_1 == null) {
                continue;
            }

            if (android.support.design.a.isTextEmpty(v0_1.getKey())) {
                continue;
            }

            if (android.support.design.a.isTextEmpty(v0_1.getValue())) {
                continue;
            }

            arg4.add(new NameValueImpl(v0_1.getKey(), v0_1.getValue()));
        }
    }

    @Deprecated
    public static String executePost(int maxLength, String url, List<NameValueImpl> nameValueList) throws Exception {
        if (!android.support.design.a.isTextEmpty(url)) {
            LinkedHashMap v3 = new LinkedHashMap();
            Pair<String, String> pair = NetworkDemo.parseUrl(url, ((Map) v3));
            String website = pair.first;
            String path = pair.second;
            INetworkApi networkApi = RetrofitUtils.createService(website, INetworkApi.class);
            LinkedHashMap<String,String> queryMap = new LinkedHashMap();
            if (nameValueList != null && !nameValueList.isEmpty()) {
                Iterator<NameValueImpl> iterator = nameValueList.iterator();
                while (iterator.hasNext()) {
                    NameValueImpl nameValue = iterator.next();
                    queryMap.put(nameValue.name, nameValue.value);
                }
            }
            AppConfig.a(queryMap);
            return networkApi != null
                    ? (String) networkApi.doPost(maxLength, path, v3, queryMap, null, null).execute().body
                    : null;
        }
        return null;
    }

    @Deprecated
    public static String doGet(int arg1, String url) throws Exception {
        return doGet(arg1, url, true);
    }

    @Deprecated
    public static String a(String arg3, String arg4, String arg5) throws Exception {
        LinkedHashMap map = new LinkedHashMap();
        map.put(arg4, new TypedFile(new File(arg5)));
        return executePostMultiPart(arg3, map);
    }

    @Deprecated
    public static String executePost(int maxLength, String url, byte[] inputBytes, CompressType compressType, String contentType) throws Exception {
        if (!android.support.design.a.isTextEmpty(url)) {
            Pair<byte[],String> bytesPair = compressWithGzip(inputBytes, compressType);
            byte[] bytes = bytesPair.first;
            String contentEncoding = bytesPair.second;
            ArrayList<Header> headerList = new ArrayList();
            if (contentEncoding != null) {
                headerList.add(new Header("Content-Encoding", ((String) contentEncoding)));
            }

            if (contentType != null && contentType.length() > 0) {
                headerList.add(new Header("Content-Type", contentType));
            }

            LinkedHashMap<String, String> queryMap = new LinkedHashMap<>();
            Pair<String, String> pair = NetworkDemo.parseUrl(url, queryMap);
            String website = pair.first;
            String path = pair.second;
            INetworkApi networkApi = RetrofitUtils.createService(website, INetworkApi.class);
            return networkApi != null ? (String) networkApi.postBody(
                    maxLength,
                    path,
                    queryMap,
                    new TypedByteArray(null, ((byte[]) bytes)),
                    headerList).execute().body : null;
        }
        return null;
    }

    public static void setUserAgent(String arg0) {
        AppConfig.a(arg0);
    }

    public static String getNetworkAccessType(NetworkType networkType) {
        return android.support.design.a.doGetNetworkAccessType(networkType);
    }

    public static void a(int arg0) {
        c = arg0;
    }

    @Deprecated
    public static boolean downloadFile(int arg11,
                                       String arg12,
                                       String arg13,
                                       String arg14,
                                       String arg15,
                                       com.bytedance.frameworks.baselib.network.http.util.d arg16,
                                       String arg17,
                                       TaskInfo taskInfo,
                                       List arg19,
                                       String[] arg20,
                                       int[] arg21) throws Exception {
        LinkedList v8 = new LinkedList();
        if (arg19 != null && !arg19.isEmpty()) {
            Iterator v1 = arg19.iterator();
            while (v1.hasNext()) {
                Object v0 = v1.next();
                ((List) v8).add(new Header(((NameValueImpl) v0).name, ((NameValueImpl) v0).value));
            }
        }
        return RetrofitUtils.downloadFile(arg11, arg12, arg13, arg14, arg15, arg16, arg17, taskInfo, v8, arg20, arg21);
    }

    @Deprecated
    public static String doGet(int arg6, String arg7, boolean arg8) throws Exception {
        return doGet(arg6, arg7, arg8, null, null, null);
    }

    @Deprecated
    public static String doGet(int maxLength,
                               String url,
                               boolean addCommonParams,
                               List<HttpHeader> httpHeaderList,
                               ResponseHeaders responseHeaders,
                               RequestParams requestContext) throws Exception {
        if (android.support.design.a.isTextEmpty(url)) {
            return null;
        } else {
            LinkedHashMap<String, String> queryMap = new LinkedHashMap();
            Pair<String, String> pair = NetworkDemo.parseUrl(url, queryMap);
            String website = pair.first;
            String path = pair.second;
            INetworkApi networkApi = RetrofitUtils.createService(website, INetworkApi.class);
            LinkedList<Header> headerList = new LinkedList<>();
            if (httpHeaderList != null && !httpHeaderList.isEmpty()) {
                Iterator<HttpHeader> iterator = httpHeaderList.iterator();
                while (iterator.hasNext()) {
                    HttpHeader httpHeader = iterator.next();
                    headerList.add(new Header(httpHeader.name(), httpHeader.value()));
                }
            }
            if (networkApi == null) {
                return null;
            } else {
                ResponseWrapper<String> responseWrapper = networkApi
                        .doGet(addCommonParams, maxLength, path, queryMap, headerList, requestContext)
                        .execute();
                if (responseHeaders != null) {
                    List<Header> responseHeaderList = responseWrapper.rawResponse.headers;
                    if (responseHeaderList != null && !responseHeaderList.isEmpty()) {
                        Iterator<Header> iterator = responseHeaderList.iterator();
                        while (iterator.hasNext()) {
                            Header header = iterator.next();
                            String name = header.name;
                            if ("ETag".equalsIgnoreCase(name)
                                    || "Last-Modified".equalsIgnoreCase(name)
                                    || "Cache-Control".equalsIgnoreCase(name)) {
                                responseHeaders.httpHeaderList.add(new LegacyHeader(header.name, ((Header) header).value));
                            }
                        }
                    }
                }
                return responseWrapper.body;
            }
        }
    }

    public static long extractMaxAge(ResponseHeaders responseHeaders) {
        int i;
        HttpHeader cacheControlHttpHeader = responseHeaders.getHeader("Cache-Control");
        if (cacheControlHttpHeader == null) {
            return -1;
        }
        try {
            c[] cArr = cacheControlHttpHeader.d();
            if (cArr == null) {
                return -1;
            }

            int v4 = cArr.length;
            i = 0;
            while (true) {
                if (i >= v4) {
                    return -1;
                }
                c item = cArr[i];
                if (!"max-age".equals(item.a())) {
                    ++i;
                    continue;
                }
                String v2_3 = item.b();
                if (v2_3 == null) {
                    return -1;
                }
                return Long.parseLong(v2_3);
            }
        } catch (Exception exception) {
            Logger.w("NetworkUtils", "extract max-age exception: " + exception);
            return -1;
        }
    }

    public static void addCacheValidationHeaders(List headerList, String ifNoneMatch) {
        if (!android.support.design.a.isTextEmpty(ifNoneMatch)) {
            headerList.add(new LegacyHeader("If-None-Match", ifNoneMatch));
        }
//        if (!android.support.design.a.isTextEmpty(ifModifiedSince)) {
//            headerList.add(new com.ss.android.http.legacy.a.a("If-Modified-Since", ifModifiedSince));
//        }
    }

    public static boolean is2g(Context arg1) {
        return android.support.design.a.a(arg1);
    }

    private static Pair<byte[],String> compressWithGzip(byte[] bytes, CompressType compressType) throws IOException {
        Pair v1_3;
        GZIPOutputStream v2;
        ByteArrayOutputStream v1_2;
        int v3 = 128;
        if (bytes == null) {
            new Pair(bytes, null);
        }

        try {
            int v1_1 = bytes.length;
            if (CompressType.GZIP == compressType && v1_1 > v3) {
                v1_2 = new ByteArrayOutputStream(8192);
                v2 = new GZIPOutputStream(v1_2);
                v2.write(bytes);
                v2.close();
                bytes = v1_2.toByteArray();
                return new Pair(bytes, "gzip");
            }

            label_42:
            if (CompressType.DEFLATER != compressType) {
                return new Pair(bytes, null);
            }

            if (v1_1 <= v3) {
                return new Pair(bytes, null);
            }

            v1_2 = new ByteArrayOutputStream(8192);
            Deflater v2_1 = new Deflater();
            v2_1.setInput(bytes);
            v2_1.finish();
            byte[] v3_1 = new byte[8192];
            while (!v2_1.finished()) {
                v1_2.write(v3_1, 0, v2_1.deflate(v3_1));
            }

            v2_1.end();
            bytes = v1_2.toByteArray();
            return new Pair(bytes, "deflate");
        } catch (Throwable v1) {
            Logger.w("NetworkUtils", "compress with gzip exception: " + v1);
            v1_3 = new Pair(bytes, null);
            return v1_3;
        }
    }

    @Deprecated
    private static String executePostMultiPart(String url, Map<String, TypedOutput> partMap) throws Exception {
        String v4 = null;
        if (!android.support.design.a.isTextEmpty(url)) {
            LinkedHashMap v3 = new LinkedHashMap();
            Pair<String, String> v1 = NetworkDemo.parseUrl(url, v3);
            String website = v1.first;
            String path = v1.second;
            INetworkApi networkApi = RetrofitUtils.createService(website, INetworkApi.class);
            LinkedList v5 = new LinkedList();
            LinkedHashMap v1_1 = new LinkedHashMap();
            AppConfig.a(((Map) v1_1));
            if (!((Map) v1_1).isEmpty()) {
                Iterator v6 = ((Map) v1_1).entrySet().iterator();
                while (v6.hasNext()) {
                    Map.Entry<String, String> v1_2 = (Map.Entry<String, String>) v6.next();
                    if (v1_2 == null) {
                        continue;
                    }
                    partMap.put(v1_2.getKey(), new TypedString(v1_2.getValue()));
                }
            }
            return networkApi != null
                    ? (String) networkApi.postMultiPart(4194304, path, v3, partMap, ((List) v5)).execute().body
                    : v4;
        }

        return v4;
    }

    public static void setTimeout(URLConnection urlConnection) {
        if (urlConnection != null) {
            urlConnection.setConnectTimeout(15000);
            urlConnection.setReadTimeout(15000);
        }
    }

    public static boolean isWifi(Context context) {
        return android.support.design.a.isWifi(context);
    }

    public static Pair<String, String> parseContentType(String arg8) {
        int v1 = 0;
        Pair v0 = null;
        if (arg8 != null) {
            c[] v2 = new LegacyHeader("Content-Type", arg8).d();
            if (v2.length != 0) {
                c v2_1 = v2[0];
                String v3 = v2_1.a();
                NameValue[] v2_2 = v2_1.c();
                if (v2_2 != null) {
                    int v4 = v2_2.length;
                    while (v1 < v4) {
                        NameValue v5 = v2_2[v1];
                        if ("charset".equalsIgnoreCase(v5.name())) {
                            String v0_1 = v5.value();
                        } else {
                            ++v1;
                            continue;
                        }
                        break;
                    }
                }

                v0 = new Pair(v3, v0);
            }
        }

        return v0;
    }

    public static boolean isNetworkAvailable(Context context) {
        return android.support.design.a.isNetworkAvailable(context);
    }

    public static NetworkType getNetworkType(Context context) {
        return android.support.design.a.getNetworkType(context);
    }

    public static String getNetworkAccessType(Context context) {
        return android.support.design.a.doGetNetworkAccessType(android.support.design.a.getNetworkType(context));
    }

    public static String getNetworkOperatorCode(Context context) {
        try {
            return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getNetworkOperator();
        } catch (Exception v0) {
            return "unkown";
        }
    }

    public static enum CompressType {
        NONE(0),
        GZIP(1),
        DEFLATER(2);

        final int nativeInt;

        CompressType(int i) {
            this.nativeInt = i;
        }
    }
}

